﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SyncChatClient
{
    public partial class MainForm : Form
    {
        private bool isExit = false;
        private TcpClient client;
        private NetworkStream networkStream;
        private BinaryReader br;
        private BinaryWriter bw;
        public MainForm()
        {
            InitializeComponent();
            Random r = new Random((int)DateTime.Now.Ticks);
            textBoxUserName.Text = "user" + r.Next(100, 999);
            listBoxOnlineStatus.HorizontalScrollbar = true;
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            buttonConnect.Enabled = false;
            try
            {
                client = new TcpClient(Dns.GetHostName(), 51888);
                AddTalkMessage("连接成功");
            }
            catch 
            {
                AddTalkMessage("连接失败");
                buttonConnect.Enabled = true;
                return;
            }
            networkStream = client.GetStream();
            br = new BinaryReader(networkStream);
            bw = new BinaryWriter(networkStream);
            SendMessage("login," + textBoxUserName.Text.ToString());
            Thread threadReceive = new Thread(ReceiveData);
            threadReceive.IsBackground = true;
            threadReceive.Start();
        }

        private void ReceiveData(object obj)
        {
            string receiveString = null;
            while (isExit==false)
            {
                try
                {
                    receiveString = br.ReadString();
                }
                catch (Exception)
                {
                    if (isExit==false)
                    {
                        MessageBox.Show("与服务器失去连接");
                    }
                    throw;
                }
                string[] splitString = receiveString.Split(',');
                string command = splitString[0].ToLower();
                switch(command)
                {
                    case "login":
                        AddOnline(splitString[1]);
                        break;
                    case "logout":
                        AddTalkMessage(splitString[1] + ":\r\n");
                        AddTalkMessage(receiveString.Substring(splitString[0].Length + splitString[1].Length + 2));
                        break;
                    default:
                        AddTalkMessage("什么意思啊：" + receiveString);
                        break;
                }
            }
            Application.Exit();
        }
        private delegate void AddOnlineDelegate(string str);
        private void AddOnline(string p)
        {
            if (listBoxOnlineStatus.InvokeRequired)
            {
                AddOnlineDelegate d = AddOnline;
                listBoxOnlineStatus.Invoke(d, new object[]{p});
            }
            else
            {
                listBoxOnlineStatus.Items.Add(p);
                listBoxOnlineStatus.SelectedIndex = listBoxOnlineStatus.Items.Count - 1;
                listBoxOnlineStatus.ClearSelected();
            }
        }

        private void SendMessage(string p)
        {
            try
            {
                bw.Write(p);
                bw.Flush();
            }
            catch (Exception)
            {
                AddTalkMessage("发送失败。");
            }
        }
        private delegate void AddTalkMessageDelegate(string str);
        private void AddTalkMessage(string p)
        {
            if (richTextBoxTalkInfo.InvokeRequired==true)
            {
                AddTalkMessageDelegate d = AddTalkMessage;
                richTextBoxTalkInfo.Invoke(d, p);
            }
            else
            {
                richTextBoxTalkInfo.ScrollToCaret();
            }
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            if (listBoxOnlineStatus.SelectedIndex!=-1)
            {
                SendMessage("Talk," + listBoxOnlineStatus.SelectedItem + "," + textBoxSend.Text + "\r\n");
                textBoxSend.Clear();
            }
            else
            {
                MessageBox.Show("请在【当前在线】中玄奇一个对话者");
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (client!=null)
            {
                SendMessage("Logout,"+textBoxUserName.Text);
                isExit = true;
                br.Close();
                bw.Close();
                client.Close();
            }
        }

        private void textBoxSend_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar==(char)Keys.Return)
            {
                buttonSend.PerformClick();
            }
        }

    }
}
